﻿using CommunityToolkit.Mvvm.Input;
using Microsoft.Win32;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImageHandler.ViewModels
{
    public class P002_IntroduceViewModel: PartViewModel
    {
        public P002_IntroduceViewModel()
        {
            Header = "使用 OpenCvSharp 读取图像文件";
            OperateCommand = new RelayCommand<string>(Execute);
        }

        private void Execute(string action)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.DefaultDirectory = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "Assert\\Images");
            openFileDialog.Filter = "Image files (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png | All files (*.*) | *.*";
            if (openFileDialog.ShowDialog() == true)
            {
                // Handle the selected file
                OperateLogAction?.Invoke($"选择文件 {openFileDialog.FileName}！");
                Run(openFileDialog.FileName);
            }

        }

        private void Run(string path)
        {
            // 读取图像
            Mat src = Cv2.ImRead(path, ImreadModes.Color);
            if (src.Empty())
            {
                OperateLogAction?.Invoke("无法读取图像！");
                return;
            }

            // 转换为灰度图像
            Mat gray = new Mat();
            Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);

            // 应用高斯模糊
            Mat blurred = new Mat();
            Cv2.GaussianBlur(gray, blurred, new OpenCvSharp.Size(5, 5), 1.5);

            // 显示原图和处理后的图像
            Cv2.ImShow("源图像", src);
            Cv2.ImShow("高斯模糊", blurred);

            // 使窗口保持打开状态，直到按下任意键
            Cv2.WaitKey(0);

            // 释放资源
            src.Dispose();
            gray.Dispose();
            blurred.Dispose();
            Cv2.DestroyAllWindows();
        }
    }
}
